package com.woniu.commons.util;

import com.woniu.zsd.commons.core.JWTUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebUtil {
    /**
     * @description: 获取请求对象tostring
     * @params: []
     * @return: javax.servlet.http.HttpServletRequest
     * @author: aheng
     * @time: 2025/3/27 16:20
     */
    public static HttpServletRequest getRequest() {
        try {
            ServletRequestAttributes attribute = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return attribute.getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @description: 获取响应对象
     * @params: []
     * @return: javax.servlet.http.HttpServletResponse
     * @author: aheng
     * @time: 2025/3/27 16:22
     */

    public static HttpServletResponse getResponse() {
        try {
            ServletRequestAttributes attribute = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return attribute.getResponse();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @description: 获取请求头的token中隐藏的userId
     * @params: []
     * @return: java.lang.String
     * @author: aheng
     * @time: 2025/4/1 15:08
     */
    public static String UserId() {
        String token = WebUtil.getRequest().getHeader("Token");
        return JWTUtil.AnalyzeToken(token).get("id").toString();
    }
}
